package config

import (
	"flag"
	"github.com/spf13/viper"
	"log"
	"path"
	"runtime"
	"strconv"
)

var Env = loadConfig(".")

func loadConfig(envPath string) envConfig {
	var cfgPath string
	flag.StringVar(&cfgPath, "c", "", "config file envPath.")
	flag.Parse()
	if cfgPath == "" {
		viper.AddConfigPath(envPath)
		viper.SetConfigFile(".env")
	} else {
		viper.SetConfigFile(cfgPath)
	}
	viper.AutomaticEnv()
	var runPath string
	if _, filename, _, ok := runtime.Caller(0); ok {
		runPath = path.Dir(path.Dir(filename))
	}
	config := envConfig{
		RootPath: runPath,
		DevMode:  false,
		GinMode:  "debug",
		// 直连
		DirectPort: 1129,
		// 服务运行端口
		ServerPort: 8000,
		// 禁止修改操作 (演示功能,限制POST请求)
		DisallowModify: false,
		// 资源访问前缀
		PublicPrefix: "/api/uploads",
		// 上传文件路径
		UploadDirectory: "/tmp/uploads/",
		// Redis源配置
		RedisUrl:      "redis://localhost:6379",
		RedisPoolSize: 100,
		RedisDb:       1,
		// 数据源配置
		DatabaseUrl:            "root:root@tcp(localhost:3306)/xakj?charset=utf8mb4&parseTime=True&loc=Local",
		DatabaseName:           "iot",
		DbTablePrefix:          "xakj_",
		DbDefaultStringSize:    256,
		DbMaxIdleConns:         10,
		DbMaxOpenConns:         100,
		DbConnMaxLifetimeHours: 2,
		// MQTT
		MqttOpen:     true,
		MqttHost:     "tcp://192.168.3.105",
		MqttPort:     1883,
		MqttUsername: "admin",
		MqttPassword: "admin",
		// 全局配置
		// 版本
		Version: "v1.1.0",
		// 系统加密字符
		Secret: "UVTIyzCy",
		// 静态资源URL路径
		StaticPath: "/api/static",
		// 静态资源本地路径
		StaticDirectory: "static",
		// Redis键前缀
		RedisPrefix: "ZDMANINI:",
		// 上传图片限制
		UploadImageSize: 1024 * 1024 * 10,
		// 上传视频限制
		UploadVideoSize: 1024 * 1024 * 30,
		// 上传文件限制
		UploadFileSize: 1024 * 1024 * 50,
		// 上传图片扩展
		UploadImageExt: []string{"png", "jpg", "jpeg", "gif", "ico", "bmp"},
		// 上传视频扩展
		UploadVideoExt: []string{"mp4", "mp3", "avi", "flv", "rmvb", "mov"},
		// 上传文件扩展
		UploadFileExt: []string{"doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf", "txt", "zip", "rar", "7z", "gz", "tar", "bz2", "cab", "jar", "apk"},
		// 自动迁移
		AutoMigrate: true,
	}
	err := viper.ReadInConfig()
	if err != nil {
		log.Fatal("loadConfig ReadInConfig err:", err)
	}
	err = viper.Unmarshal(&config)
	if err != nil {
		log.Fatal("loadConfig Unmarshal err:", err)
	}
	// PublicUrl未设置设置默认值
	if config.PublicUrl == "" {
		config.PublicUrl = "http://127.0.0.1:" + strconv.Itoa(config.ServerPort)
	}
	if config.AppId == "" {
		config.AppId = "xiaoEnergy"
	}
	return config
}
